package day9;

import java.util.Random;

/**
 * @author oldliu
 * @since 1.0
 */
public class MoneyTaker extends Thread {
    private final Accout ac;

    public MoneyTaker(String name, Accout ac) {
        super(name);
        this.ac = ac;
    }

    @Override
    public void run() {
        Random r = new Random();

        while (true) {
            int qu = r.nextInt(200);//0-200,要取的钱数
            System.out.println(getName() + "计划取钱：" + qu);
            try {
                synchronized (ac) {
                    while (ac.getMoney() < qu) {
                        System.out.println(getName() + "发现钱不够,等着,现在余额是"+ac.getMoney());
                        ac.wait();//等待存钱的人发通知
                        System.out.println(getName() + "被喊醒，检查一下钱够不够！");
                    }
                    ac.takeAway(qu);
                    System.out.println(getName() + "取钱"+qu+"成功，现在余额是" + ac.getMoney() + "元");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
